package com.leo.interview;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 7.启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:
 线程1: 1
 线程1: 2
 线程1: 3
 线程1: 4
 线程1: 5

 线程2: 6
 线程2: 7
 线程2: 8
 线程2: 9
 线程2: 10
 ...

 线程3: 71
 线程3: 72
 线程3: 73
 线程3: 74
 线程3: 75

 处理边界条件有点烦，其他还是不错的
 * @author xuexiaolei
 * @version 2017年11月14日
 */
public class Interview7 {
    private static final Object lock = new Object();
    private static final AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(3);
        exec.execute(new Task("线程1", 0));
        exec.execute(new Task("线程2", 1));
        exec.execute(new Task("线程3", 2));
        exec.shutdown();
    }

    static class Task implements Runnable {
        private final String threadName;
        private final int count;
        Task(String threadName, int count) {
            this.threadName = threadName;
            this.count = count;
        }

        @Override public void run() {
            do {
                synchronized (lock) {
                    while ((counter.get()/5)%3 != count) {//counter每次输出完成肯定是5的倍数，除以5然后对3取余判断是否是当前线程来写
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    for (int i = 0; i < 5; i++) {
                        System.out.println(threadName+":"+counter.incrementAndGet());
                    }
                    lock.notifyAll();
                }
            } while (counter.get() < 65);
        }
    }
}
